package refactoringtofuturetask.popup.actions;

import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodWizard;
import org.eclipse.jdt.ui.refactoring.RefactoringSaveHelper;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorPart;

import refactoringtofuturetask.refactorings.ConvertToFutureTaskRefactoring;
import refactoringtofuturetask.ui.ConvertToFutureTaskWizard;

public class ConvertToFTEditorAction implements IEditorActionDelegate {

	private JavaEditor fEditor;
	private ITextSelection tSelection;

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		if (!ActionUtil.isEditable(fEditor))
			return;
		ConvertToFutureTaskRefactoring refactoring = new ConvertToFutureTaskRefactoring(
				SelectionConverter.getInputAsCompilationUnit(fEditor),
				tSelection.getOffset(), tSelection.getLength());
		new RefactoringStarter().activate(new ConvertToFutureTaskWizard(
				refactoring, "Convert to FutureTask"), getShell(),
				"Convert to FutureTask", RefactoringSaveHelper.SAVE_NOTHING);
		// MessageDialog.openInformation(getShell(), "RefactoringToFutureTask",
		// "ConvertToFutureTask Editor Action was executed.");
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof ITextSelection)
			tSelection = (ITextSelection) selection;

		// RefactoringWizardOpenOperation operation = new
		// RefactoringWizardOpenOperation(
		// new ConvertToFutureTaskWizard(refactoring,
		// "Convert to FutureTask"));
		// try {
		// operation.run(getShell(), "Convert to FutureTask");
		// } catch (InterruptedException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	@Override
	public void setActiveEditor(IAction action, IEditorPart targetEditor) {
		if (targetEditor instanceof JavaEditor) {
			fEditor = (JavaEditor) targetEditor;
		}
	}

	private Shell getShell() {
		return fEditor.getSite().getShell();
	}
}
